=begin pod :kind("Language") :subkind("Language") :category("fundamental")

=TITLE Variables

=SUBTITLE Variables in Raku

Variables are symbolic names for values or L<containers|/language/containers>.
Variable declarations or assignment of values may create a container on the fly.
Variable names can start with or without a special character called a I<sigil>,
followed optionally by a second special character named I<twigil> and then an
L<identifier|/language/syntax#Identifiers>.


=head1 Sigils
X<|sigil,$>X<|sigil,@>X<|sigil,%>X<|sigil,&>

There are four sigils. The scalar-sigil C<$>, the positional-sigil C<@>, the
associative-sigil C<%> and the callable-sigil C<&>.

Sigils provide a link between syntax, the type system and
L<containers|/language/containers>. They provide a shortcut for the most
common type constraints when declaring variables, and serve as markers
for L<string interpolation|/language/quoting#Interpolation:_qq>. The
L<positional-sigil|/language/containers#Flattening,_items_and_containers>
and the
L<associative-sigil|/language/containers#Flattening,_items_and_containers>
provide type constraint that enforce base type
L<subscripts|/language/subscripts#TOC_Title> required to know what
methods to dispatch to. The
L<callable-sigil|/language/containers#Callable_containers> does the same
for function calls. The latter also tells the compiler where parentheses
for calls can be omitted. The positional and associative-sigil also
simplify assignment by flattening by default.

=begin table

Sigil   Type constraint          Default type  Assignment  Examples
=====   ===============          ============  ==========  ========
$       Mu (no type constraint)  Any           item        Int, Str, Array, Hash
@       Positional               Array         list        List, Array, Range, Buf
%       Associative              Hash          list        Hash, Map, Pair
&       Callable                 Callable      item        Sub, Method, Block, Routine

=end table

Examples:

    my $square = 9 ** 2;
    my @array  = 1, 2, 3;   # Array variable with three elements
    my %hash   = London => 'UK', Berlin => 'Germany';

X<|is (type of variable)>
The type to which the variable will be bound can be set with C<is> in the
declaration of the variable.  Assuming we have a C<FailHash> class:

    class FailHash is Hash {
        has Bool $!final = False;
        multi method AT-KEY ( ::?CLASS:D: Str:D \key ){
            fail X::OutOfRange.new(:what("Hash key"), :got(key),
              :range(self.keys)) if $!final && !self.EXISTS-KEY(key);
            callsame  # still not final, so do normal action from Hash
        }

        method finalize() {
            $!final = True
        }
    }

One can then define a C<%h> variable of this type using C<is>:

=for code :preamble<class FailHash {}>
my %h is FailHash = oranges => "round", bananas => "bendy";

And then run the following code:

=for code :preamble<my %h>
say %h<oranges>;
# OUTPUT: «round␤»
%h.finalize;
say %h<cherry>;
CATCH { default { put .^name, ': ', .Str } }
# OUTPUT: «X::OutOfRange: Hash key out of range. Is: cherry, should be in (oranges bananas)»

For information on variables without sigils, see
L<sigilless variables|#Sigilless_variables>.

=head2 Item and list assignment

There are two types of variable assignment, I<item assignment> and I<list
assignment>.

An item assignment copies a single value from the right-hand side into a Scalar
variable on the left. An assignment to anything other than a simple Scalar
variable is parsed as a list assignment. A list assignment leaves the choice of
what the assignment operation entails to the variable on the left. For example,
L<Array|/type/Array> variables (C<@> sigil) empty themselves on list assignment,
and then iteratively copy all values from the right-hand side into themselves as
elements.

The two types of assignment both use the equal sign C<=> as their operator and
are both right associative, but differ in operator precedence: item assignment
has a higher precedence level (level: Item assignment) than list assignment
(level: List prefix). In situations in which a comma-separated list of elements
is assigned, these precedences should in particular be contrasted with that of
the comma operator C<,> which sits in between. So without any list-delimiting
parentheses (or other construct to hold the list's elements together), item
assignment will only assign the first element of the specified list, and not the
full list.

In an assignment expression the context of the left-hand side determines whether
an C<=> means item or list assignment. As mentioned, item assignment is
restricted to simple Scalar variables. Accordingly, assignment to a Scalar
container (scalar-context) triggers item assignment, unless the Scalar is
explicitly put in list-context by surrounding parentheses C<( )>:

    my $a;
    $a = 1,2,3;        # item assignment to Scalar
    say $a;            # OUTPUT: «1␤» ( '=' has higher precedence than ',' )

    my $b = 1,2,3;     # item assignment to Scalar (same as preceding example)
    say $b;            # OUTPUT: «1␤»

    my $c;
    ($c) = 4,5,6;      # list assignment to Scalar; '( )' is list-contextualizer
    say $c;            # OUTPUT:  «(4,5,6)␤»

    (my $d) = 4,5,6;   # list assignment to Scalar (same as preceding example)
    say $d;            # OUTPUT:  «(4,5,6)␤»

Assignment to a List container (list-context) always triggers list assignment:

    my @e;
    @e = 7,8,9;                    # list assignment to Array
    say @e;                        # OUTPUT:  «[7,8,9]␤»

    my $f;
    ($f,) = 7,8,9;                 # list assignment to List with one element
    say $f;                        # OUTPUT:  «7␤»
    say ( ($f,) ).VAR.^name;       # OUTPUT:  «List␤»

    # ATTENTION: special declaration syntax!
    my ($g) = 7,8,9;               # list assignment to List with one element
    say $g;                        # OUTPUT:  «7␤»
    say ( ($g) ).VAR.^name         # OUTPUT:  «List␤»

The last two examples above are simple I<destructuring assignments> that select
the first item of the right-hand side list. See for a more elaborate discussion
of destructuring assignments in the context of variable declarations the section
on L<declaring a list of variables with lexical or package
scope|/language/variables#index-entry-declaring_a_list_of_variables>.

Chained assignments are parsed having regard to the precedence of the assignment
operators and, where applicable, their right associativity. For instance, in the
example below there is one chained assignment statement comprising two
assignment operators. The assignment to C<@array> is a list assignment having a
lower precedence than the item assignment to the Scalar variable C<$num>. The
assignment expression involving the item assignment to the Scalar variable
C<$num> is thus evaluated first. It returns the assigned value C<42>, which in
turn forms part of the List C<(42, "str")> constructed by the comma operator
that also has a higher precedence than the list assignment. Finally, the
List C<(42, "str")> is list-assigned to C<@array>:

    my @array;
    @array = my $num = 42, "str";   # parsed as @array = ( (my $num = 42), "str )
    say @array.raku;                # OUTPUT: «[42, "str"]␤» (an Array)
    say $num.raku;                  # OUTPUT: «42␤» (a Num)

Here's a variant:

    my ( @foo, $bar );
    @foo = ($bar) = 42, "str";       # parsed as @foo = ( $bar = (42, "str") )
    say $bar.raku;                   # OUTPUT: «$(42, "str")␤» (a List)#
    say @foo.raku;                   # OUTPUT: «[(42, "str"),]␤» (an Array)

In this case, the list contextualizer C<( )> puts C<$bar> in a list context, and
thus triggers a list assignment to the Scalar variable C<$bar>. This means that
there are two chained list assignments, both having a lower precedence than the
comma operator C<,> that constructs the List C<(42, "str")>. Due to their right
associativity, the list assignment expression that is evaluated first is the
assignment to C<$bar>, which returns the assigned value C<$(42, "str")>, i.e. a
Scalar containing a two-element List. This value is in turn list-assigned to
C<@array>, such that it becomes a Array with a single element, namely a List.

See L<operators|/language/operators> for more details on precedence and
associativity.

=head2 Sigilless variables
X<|\ (sigilless variables)>

Using the C<\> prefix, it's possible to create variables that do not
have a sigil:

    my \degrees = pi / 180;
    my \θ       = 15 * degrees;

Note that sigilless variable do not have associated
L<containers|/language/containers>. This means C<degrees> and C<θ>, above,
actually directly represent C<Num>s. To illustrate, try assigning to one after
you've defined it:

=begin code :skip-test<dies deliberately>
θ = 3; # Dies with the error "Cannot modify an immutable Num"
=end code

Sigilless variables do not enforce L<context|/language/contexts>, so they can be
used to pass something on as-is:

    sub logged(&f, |args) {
        say('Calling ' ~ &f.name ~ ' with arguments ' ~ args.raku);
        my \result = f(|args);
        #  ^^^^^^^ not enforcing any context here
        say(&f.name ~ ' returned ' ~ result.raku);
        return |result;
    }

Sigilless variables can also be used for binding.
See L<Binding|/language/containers#Binding> for more information.

=head1 Twigils
X<|Twigil>

We use the term twigils, a word play with I<sigil>, that indicates it uses two
symbols in front of an identifier; the second symbol will be placed between
the sigil and the identifier, and it will be related to the scoping of a
variable, that is, where that variable is defined and can be changed.

=begin table

    Twigil  Scope
    ======  =====
     none   Based only on declarator
     *      Dynamic
     ?      Compile-time variable
     !      Attribute (class member)
     .      Method (not really a variable)
     <      Index into match object (not really a variable)
     ^      Self-declared formal positional parameter
     :      Self-declared formal named parameter
     =      Pod variables
     ~      The sublanguage seen by the parser at this lexical spot

=end table

X<|Dynamically scoped variables>
=head2 The C<*> twigil
X<|twigil,*>X<|twigil,$*>X<|twigil,@*>X<|twigil,%*>X<|twigil,&*>

This twigil is used for dynamic variables which are looked up through the
caller's, not through the outer, scope. Look at the example below.N<The example
below cannot run correctly in the REPL, yielding an error about not finding the
dynamic variables. Please test it by copy-pasting it into a file, then run the
file.>

=begin code
my $lexical   = 1;
my $*dynamic1 = 10;
my $*dynamic2 = 100;

sub say-all() {
    say "$lexical, $*dynamic1, $*dynamic2";
}

say-all();    # OUTPUT: 1, 10, 100

{
    my $lexical   = 2;
    my $*dynamic1 = 11;
    $*dynamic2    = 101;

    say-all(); # OUTPUT: 1, 11, 101
}

say-all();  # OUTPUT: 1, 10, 101
=end code

The first time C<&say-all> is called, it prints "C<1, 10, 100>" just as one
would expect. The second time though, it prints "C<1, 11, 101>". This is
because C<$lexical> isn't looked up in the caller's scope but in the scope
C<&say-all> was defined in. The two dynamic variables are looked up in the
caller's scope and therefore have the values C<11> and C<101>. The third
time C<&say-all> is called C<$*dynamic1> isn't C<11> anymore, but
C<$*dynamic2> is still C<101>. This stems from the fact that we declared a
new dynamic variable C<$*dynamic1> in the block and did not assign to the
old variable as we did with C<$*dynamic2>.

The dynamic variables differ from other variable types in that referring
to an undeclared dynamic variable is not a compile time error but a
runtime L<failure|/type/Failure>, so a dynamic variable can be used
undeclared as long as it's checked for definedness or used in a
Boolean context before using it for anything else:

=begin code
sub foo() {
    $*FOO // 'foo';
}

say foo; # OUTPUT: «foo␤»

my $*FOO = 'bar';

say foo; # OUTPUT: «bar␤»
=end code

Dynamic variables can have lexical scope when declared with C<my> or package
scope when declared with C<our>. Dynamic resolution and resolution through
symbol tables introduced with C<our> are two orthogonal issues.


=head2 The C<?> twigil
X<|twigil,?>X<|twigil,$?>X<|twigil,@?>X<|twigil,%?>X<|twigil,&?>

Compile-time variables may be addressed via the C<?> twigil. They are known
to the compiler and may not be modified after being compiled in. A popular
example for this is:

    say "$?FILE: $?LINE"; # OUTPUT: "hello.p6: 23"
                          # if this is the line 23 of a
                          # file named "hello.p6"

For a list of these special variables, see
L<compile-time variables|/language/variables#Compile-time_variables>.

=head2 The C<!> twigil
X<|twigil,!>X<|twigil,$!>X<|twigil,@!>X<|twigil,%!>X<|twigil,&!>

L<Attributes|/language/objects#Attributes> are variables that exist per instance
of a class. They may be directly accessed from within the class via C<!>:

    my class Point {
        has $.x;
        has $.y;

        method Str() {
            "($!x, $!y)"
        }
    }

Note how the attributes are declared as C<$.x> and C<$.y> but are still
accessed via C<$!x> and C<$!y>. This is because in Raku all attributes are
private and can be directly accessed within the class by using
C<$!attribute-name>. Raku may automatically generate accessor methods for
you though. For more details on objects, classes and their attributes see
L<object orientation|/language/objects>.


=head2 The C<.> twigil
X<|twigil,.>X<|twigil,$.>X<|twigil,@.>X<|twigil,%.>X<|twigil,&.>

The C<.> twigil isn't really for variables at all. In fact, something along
the lines of

    my class Point {
        has $.x;
        has $.y;

        method Str() {
            "($.x, $.y)" # note that we use the . instead of ! this time
        }
    }

just calls the methods C<x> and C<y> on C<self>, which are automatically
generated for you because you used the C<.> twigil when the attributes were
declared.  Note, however, that subclasses may override those methods. If you
don't want this to happen, use C<$!x> and C<$!y> instead.

The fact that the C<.> twigil does a method call implies that the following
is also possible:

    class SaySomething {
        method a() { say "a"; }
        method b() { $.a; }
    }

    SaySomething.b; # OUTPUT: «a␤»

For more details on objects, classes and their attributes and methods see
L<object orientation|/language/objects>.

=head2 The C<^> twigil
X<|twigil,^>X<|twigil,$^>X<|twigil,@^>X<|twigil,%^>X<|twigil,&^>


The C<^> twigil declares a formal positional parameter to blocks or subroutines;
that is, variables of the form C<$^variable> are a type of placeholder variable.
They may be used in bare blocks to declare formal parameters to that block. So
the block in the code

    my @powers-of-three = 1,3,9…100;
    say reduce { $^b - $^a }, 0, |@powers-of-three;
    # OUTPUT: «61␤»

has two formal parameters, namely C<$a> and C<$b>. Note that even though C<$^b>
appears before C<$^a> in the code, C<$^a> is still the first formal parameter
to that block. This is because the placeholder variables are sorted in Unicode
order.

Although it is possible to use nearly any valid identifier as a placeholder
variable, it is recommended to use short names or ones that can be trivially
understood in the correct order, to avoid surprise on behalf of the reader.

Normal blocks and subroutines may also make use of placeholder variables but
only if they do not have an explicit parameter list.

=begin code :skip-test<illustrates error>
sub say-it    { say $^a; } # valid
sub say-it()  { say $^a; } # invalid
              { say $^a; } # valid
-> $x, $y, $x { say $^a; } # invalid
=end code

Placeholder variables cannot have type constraints or a variable name with a
single upper-case letter (this is disallowed to enable catching some
Perl-isms).

The C<^> twigil can be combined with any sigil to create a placeholder variable
with that sigil.  The sigil will have its normal semantic effects, as described
in the L<Sigils table|#Sigils>. Thus C<@^array>, C<%^hash>, and C<&^fun> are all
valid placeholder variables.


=head2 The C<:> twigil
X<|twigil,:>X<|twigil,$:>X<|twigil,@:>X<|twigil,%:>X<|twigil,&:>

The C<:> twigil declares a formal named parameter to a block or subroutine.
Variables declared using this form are a type of placeholder variable too.
Therefore the same things that apply to variables declared using the C<^>
twigil also apply here (with the exception that they are not positional and
therefore not ordered using Unicode order, of course). For instance:

    say { $:add ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add
    # OUTPUT: «-1␤»

See L<^|/syntax/$CIRCUMFLEX_ACCENT> for more details about placeholder variables.

=head3 A note on C<^> and C<:>

Unlike other twigils, C<^> and C<:> I<declare> variables, which can then be
referred to without that twigil.  Thus, the previous example could be written as:

    say { $:add ?? $^a + $^b !! $a - $b }( 4, 5 ) :!add      # OUTPUT: «-1␤»

That is, once you have used C<$^a> to declare C<$a>, you can refer to that variable
in the same scope with I<either> C<$^a> or C<$a>.  The same is true for C<:>: after
declaring C<$:add>, you are free to refer to that declared variable with C<$add> if
you prefer.

In some instances, this is just a convenience – but it can be much more significant
when dealing with nested blocks.  For example:

    { say $^a; with "inner" { say $^a } }("outer");       # OUTPUT: «outer␤inner␤»
    { say $^a; with "inner" { say $a } }("outer");        # OUTPUT: «outer␤outer␤»

The first line declares I<two> formal positional parameters, while the second declares
only one (but refers to it twice).  This can be especially significant with constructs
such as C<with>, C<for>, and C<if> that are often used without much consideration of
the fact that they create blocks.

Just like the C<^>twigil, the C<:> twigil can be combined with any sigil; using
C<:> with a sigil will create a formal named parameter with that sigil (applying
the L<semantics of that sigil|#Sigil>).  Thus C<@:array>, C<%:hash>, and
C<&:fun> are all valid, and each creates a formal named parameter with the
specified sigil.

=head2 The C<=> twigil
X<|twigil,=>X<|twigil,$=>X<|twigil,@=>X<|twigil,%=>X<|twigil,&=>

The C<=> twigil is used to access Pod variables. Every Pod block in the
current file can be accessed via a Pod object, such as C<$=data>,
C<$=SYNOPSIS> or C<=UserBlock>. That is: a variable with the same name of
the desired block and a C<=> twigil.

  =begin code
    =begin code
    =begin Foo
    ...
    =end Foo

    #after that, $=Foo gives you all Foo-Pod-blocks
    =end code
  =end code

You may access the Pod tree which contains all Pod structures as a
hierarchical data structure through C<$=pod>.

Note that all those C<$=someBlockName> support the C<Positional> and the
C<Associative> roles.

=head2 The C<~> twigil
X<|twigil,$~>X<|twigil,~>

The C<~> twigil is for referring to sublanguages (called slangs). The
following are useful:

X<|$~MAIN>X<|$~Quote>X<|$~Quasi>X<|$~Regex>X<|$~Trans>X<|$~P5Regex>

=begin table
    $~MAIN       the current main language (e.g., Raku statements)
    $~Quote      the current root of quoting language
    $~Quasi      the current root of quasiquoting language
    $~Regex      the current root of regex language
    $~Trans      the current root of transliteration language
    $~P5Regex    the current root of the Perl regex language
=end table

You C<augment> these languages in your current lexical scope.

=begin code :solo
use MONKEY-TYPING;
augment slang Regex {  # derive from $~Regex and then modify $~Regex
    token backslash:std<\Y> { YY };
}
=end code

X<|supersede>
=head1 Variable declarators and scope

Most of the time it's enough to create a new variable using the C<my>
keyword:

    my $amazing-variable = "World";
    say "Hello $amazing-variable!"; # OUTPUT: «Hello World!␤»

However, there are many declarators that change the details of scoping
beyond what L<#Twigils> can do.

=for table
    Declarator    Effect
    ==========    ======
    my            Introduces lexically scoped names
    our           Introduces package-scoped names
    has           Introduces attribute names
    anon          Introduces names that are private to the construct
    state         Introduces lexically scoped but persistent names
    augment       Adds definitions to an existing name
    supersede     Replaces definitions of an existing name

There are also two prefixes that resemble declarators but act on
predefined variables:

=for table
    Prefix    Effect
    ======    ======
    temp      Restores a variable's value at the end of scope
    let       Restores a variable's value at the end of scope if the block exits unsuccessfully
    constant  Declares that a container value is not going to change during its lifetime

=head2 The C<my> declarator

Declaring a variable with C<my> gives it lexical scope. This means it only
exists within the current block. For example:

=begin code :skip-test<illustrates error>
{
    my $foo = "bar";
    say $foo; # OUTPUT: «"bar"␤»
}
say $foo; # Exception! "Variable '$foo' is not declared"
=end code

This dies because C<$foo> is only defined as long as we are in the same
scope.

In order to create more than one variable with a lexical scope in the same
sentence surround the variables with parentheses:

   my ( $foo, $bar );

see also L<Declaring a list of variables with lexical or package scope|/language/variables#index-entry-declaring_a_list_of_variables>.

Additionally, lexical scoping means that variables can be temporarily
redefined in a new scope:

    my $location = "outside";

    sub outer-location {
        # Not redefined:
        say $location;
    }

    outer-location; # OUTPUT: «outside␤»

    sub in-building {
        my $location = "inside";
        say $location;
    }

    in-building;    # OUTPUT: «inside␤»

    outer-location; # OUTPUT: «outside␤»

If a variable has been redefined, any code that referenced the outer
variable will continue to reference the outer variable. So here,
C<&outer-location> still prints the outer C<$location>:

=begin code :skip-test<continued example>
sub new-location {
    my $location = "nowhere";
    outer-location;
}

new-location; # OUTPUT: «outside␤»
=end code

To make C<new-location()> print C<nowhere>, make C<$location> a dynamic variable
using L<the * twigil|#The_*_Twigil>. This twigil makes the compiler look up the
symbol in the calling scope instead of the outer scope after trying the local
scope.

C<my> is the default scope for subroutines, so C<my sub x() {}> and
C<sub x() {}> do exactly the same thing.

=head2 The C<our> declarator

C<our> variables work just like C<my> variables, except that they also
introduce an alias into the symbol table.

    module M {
        our $Var;
        # $Var available here
    }

    # Available as $M::Var here.

In order to create more than one variable with package scope,
at the same time, surround the variables with parentheses:

   our ( $foo, $bar );

see also L<the section on declaring a list of variables with lexical or package scope|/language/variables#index-entry-declaring_a_list_of_variables>.

X<|declaring a list of variables>
=head2 Declaring a list of variables with lexical (C<my>) or package (C<our>) scope

It is possible to scope more than one variable at a time, but both C<my>
and C<our> require variables to be placed into parentheses:

    my  (@a,  $s,  %h);   # same as my @a; my $s; my %h;
    our (@aa, $ss, %hh);  # same as our @aa; our $ss; our %hh;

This can be used in conjunction with X«destructuring assignment». Any
assignment to such a list will take the number of elements provided in the left
list and assign corresponding values from the right list to them. Any missing
elements are left will result in undefined values according to the type of the
variables.

    my (Str $a, Str $b, Int $c) = <a b>;
    say [$a, $b, $c].raku;
    # OUTPUT: «["a", "b", Int]␤»

To destructure a list into a single value, create a list literal with one
element by using C<($var,)>. When used with a variable declarator, providing
parentheses around a single variable is sufficient.

    sub f { 1,2,3 };
    my ($a) = f;
    say $a.raku;
    # OUTPUT: «1␤»

To skip elements in the list use the anonymous state variable C<$>.

    my ($,$a,$,%h) = ('a', 'b', [1,2,3], {:1th});
    say [$a, %h].raku;
    # OUTPUT: «["b", {:th(1)}]␤»

=head2 The C<has> declarator

C<has> scopes attributes to instances of a class or role, and methods to
classes or roles. C<has> is implied for methods, so C<has method x() {}>
and C<method x() {}> do the same thing.

See L<object orientation|/language/objects> for more documentation and some
examples.

=head2 The C<anon> declarator

The C<anon> declarator prevents a symbol from getting installed in the lexical
scope, the method table and everywhere else.

For example, you can use it to declare subroutines which know their own name,
but still aren't installed in a scope:

    my %operations =
        half   => anon sub half($x) { $x / 2 },
        square => anon sub square($x) { $x * $x },
        ;
    say %operations<square>.name;       # square
    say %operations<square>(8);         # 64

Since it is a declarator, it can be applied anywhere anything is declared, for
instance for classes or even sigilless variables.

    say anon class þ {};     # OUTPUT: «(þ)␤»
    say anon sub þ  { 42 };  # OUTPUT: «&þ␤»

Since these symbols are not installed in the scope, they can't be used by name.
They are useful, however, if they need to be assigned to an external variable
and they need to know their own name, but this can be retrieved using
introspection.

=for code
my $anon-class = anon class {
    has $.bar;
    method equal( ::?CLASS $foo ) {
      return $foo.bar == $.bar;
    }
};
say $anon-class.new( :3bar).equal( $anon-class.new( :3bar ) );
# OUTPUT: «True␤»




=head2 The C<state> declarator

C<state> declares lexically scoped variables, just like C<my>. However,
initialization happens exactly once, the first time the initialization
is encountered in the normal flow of execution. Thus, state variables
will retain their value across multiple executions of the enclosing
block or routine.

Therefore, the subroutine

    sub a {
        state @x;
        state $l = 'A';
        @x.push($l++);
    };

    say a for 1..6;

will continue to increment C<$l> and append it to C<@x> each time it is
called. So it will output:

=for code :lang<text>
[A]
[A B]
[A B C]
[A B C D]
[A B C D E]
[A B C D E F]

Since they have a lexical scope, they are tied to the block in which they are
declared.

=for code
sub foo () {
  for 0..1 {
    state $foo = 1;
    say $foo++;
  }
};
foo;  # OUTPUT: «1␤2␤»
foo;  # OUTPUT: «1␤2␤»

In this case, a new state variable is created every time the block that
runs the for loop is entered, which is why the state variable is reset
in every call to C<foo>.

This works per "clone" of the containing code object, as in this
example:

=for code
({ state $i = 1; $i++.say; } xx 3).map: {$_(), $_()}; # says 1 then 2 thrice

Note that this is B<not> a thread-safe construct when the same clone of
the same block is run by multiple threads.  Also remember that methods
only have one clone per class, not per object.

As with C<my>, a declaration of multiple C<state> variables must be placed
in parentheses which can be omitted for a single variable.

Many operators come with implicit binding which can lead to actions at a
distance.

Use C<.clone> or coercion to create a new container that can be bound to.

    my @a;
    my @a-cloned;
    sub f() {
        state $i;
        $i++;
        @a       .push: "k$i" => $i;
        @a-cloned.push: "k$i" => $i.clone;
    };

    f for 1..3;
    say @a;        # OUTPUT: «[k1 => 3 k2 => 3 k3 => 3]␤»
    say @a-cloned; # OUTPUT: «[k1 => 1 k2 => 2 k3 => 3]␤»

State variables are shared between all threads. The result can be unexpected.

    sub code(){ state $i = 0; say ++$i; $i };
    await
        start { loop { last if code() >= 5 } },
        start { loop { last if code() >= 5 } };

    # OUTPUT: «1␤2␤3␤4␤4␤3␤5␤»
    # OUTPUT: «2␤1␤3␤4␤5␤»
    # many other more or less odd variations can be produced

X<|anon state variables>X<|nameless variables>X<|$ (variable)>
=head3 The C<$> variable

In addition to explicitly declared named state variables, C<$> can be used
as an anonymous state variable without an explicit C<state> declaration.

    say "1-a 2-b 3-c".subst(:g, /\d/, {<one two three>[$++]});
    # OUTPUT: «one-a two-b three-c␤»

Furthermore, state variables can be used outside of subroutines. You
could, for example, use C<$> in a one-liner to number the lines in a file.

=begin code :lang<shell>
raku -ne 'say ++$ ~ " $_"' example.txt
=end code

Each reference to C<$> within a lexical scope is in effect a separate
variable.

=begin code :lang<shell>
raku -e '{ say ++$; say $++  } for ^5'
# OUTPUT: «1␤0␤2␤1␤3␤2␤4␤3␤5␤4␤»
=end code

That is why, if you need to reference the same $ variable (or, for that matter,
any of the other anon state variables C<@> and C<%>) more than once, a possible
solution is to bind another variable to it, although in this example it would be
more straightforward to just declare state $x and not use the magical/anonymous
C<$> variable:

=begin code
sub foo () {
    my $x := $;
    $x++;
    say $x;
    $x = $x + 1;
}

foo() for ^3; # OUTPUT: «1␤3␤5␤»
=end code

In general, it is better style to declare a named state variable in case you
have to refer to it several times.

Note that the implicit state declarator is only applied to the variable
itself, not the expression that may contain an initializer. If the
initializer has to be called exactly once, the C<state> declarator has to be
provided.

=begin code
for ^3 {       $ = .say } # OUTPUT: «0␤1␤2␤»
for ^3 { state $ = .say } # OUTPUT: «0␤»
=end code

=head3 The C<@> variable

Similar to the C<$> variable, there is also a L<Positional|/type/Positional>
anonymous state variable C<@>.

    sub foo($x) {
        say (@).push($x);
    }

    foo($_) for ^3;

    # OUTPUT: «[0]
    #          [0 1]
    #          [0 1 2]␤»

The C<@> here is parenthesized in order to disambiguate the expression
from a class member variable named C<@.push>.  Indexed access doesn't
require this disambiguation but you will need to copy the value in order
to do anything useful with it.

    sub foo($x) {
        my $v = @;
        $v[$x] = $x;
        say $v;
    }

    foo($_) for ^3;

    # OUTPUT: «[0]
    #          [0 1]
    #          [0 1 2]␤»

As with C<$>, each mention of C<@> in a scope introduces a new anonymous
array.

=head3 The C<%> variable

In addition, there's an L<Associative|/type/Associative> anonymous state
variable C<%>.

    sub foo($x) {
        say (%).push($x => $x);
    }

    foo($_) for ^3;

    # OUTPUT: «{0 => 0}
    #          {0 => 0, 1 => 1}
    #          {0 => 0, 1 => 1, 2 => 2}␤»

The same caveat about disambiguation applies. As you may expect, indexed
access is also possible (with copying to make it useful).

    sub foo($x) {
        my $v = %;
        $v{$x} = $x;
        say $v;
    }

    foo($_) for ^3;

    # OUTPUT: «{0 => 0}
    #          {0 => 0, 1 => 1}
    #          {0 => 0, 1 => 1, 2 => 2}␤»

As with the other anonymous state variables, each mention of C<%> within a
given scope will effectively introduce a separate variable.

=head2 The C<augment> declarator

With C<augment>, you can add methods, but not attributes, to existing classes and
grammars, provided you activated the C<MONKEY-TYPING> pragma first.

Since classes are usually C<our> scoped, and thus global, this means modifying
global state, which is strongly discouraged. For almost all situations, there
are better solutions.

    # don't do this
    use MONKEY-TYPING;
    augment class Int {
        method is-answer { self == 42 }
    }
    say 42.is-answer;       # OUTPUT: «True␤»

(In this case, the better solution would be to use a
L<function|/language/functions>).

=head2 The C<temp> prefix

Like C<my>, C<temp> restores the old value of a variable at the end of its
scope. However, C<temp> does not create a new variable.

    my $in = 0; # temp will "entangle" the global variable with the call stack
                # that keeps the calls at the bottom in order.
    sub f(*@c) {
        (temp $in)++;
         "<f>\n"
         ~ @c».indent($in).join("\n")
         ~ (+@c ?? "\n" !! "")
         ~ '</f>'
    };
    sub g(*@c) {
        (temp $in)++;
        "<g>\n"
        ~ @c».indent($in).join("\n")
        ~ (+@c ?? "\n" !! "")
        ~ "</g>"
    };
    print g(g(f(g()), g(), f()));

    # OUTPUT: «<g>
    #           <g>
    #            <f>
    #             <g>
    #             </g>
    #            </f>
    #            <g>
    #            </g>
    #            <f>
    #            </f>
    #           </g>
    #          </g>␤»

=head2 The C<let> prefix

Restores the previous value if the block exits unsuccessfully. A
successful exit means the block returned a defined value or a list.

    my $answer = 42;

    {
        let $answer = 84;
        die if not Bool.pick;
        CATCH {
            default { say "it's been reset :(" }
        }
        say "we made it 84 sticks!";
    }

    say $answer;

In the above case, if the C<Bool.pick> returns true, the answer will
stay as 84 because the block returns a defined value (C<say> returns
C<True>). Otherwise the C<die> statement will cause the block to exit
unsuccessfully, resetting the answer to 42.

X<|constant (Prefix)>
X<|constants (syntax)>
=head2 The C<constant> prefix

The C<constant> prefix declares that the value it tags is not going to change
during its lifetime.

=begin code
constant $pi2 = pi * 2;
$pi2 = 6; # OUTPUT: «(exit code 1) Cannot assign to an immutable value␤
=end code

The value is assigned at compile time. Since Raku modules are L<precompiled
automatically|/language/compilation>, constants defined in modules are not
re-evaluated when the program is run. Please check
L<the section on constants in the Terms page|/language/terms#Constants> for
additional information.

=head1 Type constraints and initialization

Variables have a type constraint via the L<container|/language/containers> they
are bound to, which goes between the declarator and the variable name. The
default type constraint is L<Mu|/type/Mu>. You can also use the trait
L<of|/type/Variable#trait_of> to set a type constraint.

=for code :skip-test<compilation error>
    my Int $x = 42;
    $x = 'a string';
    CATCH { default { put .^name, ': ', .Str } }
    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $x;
    expected Int but got Str ("a string")␤»

If a scalar variable has a type constraint but no initial value, it's
initialized with the type object of the default value of the container it's
bound to.

    my Int $x;
    say $x.^name;       # OUTPUT: «Int␤»
    say $x.defined;     # OUTPUT: «False␤»

Scalar variables without an explicit type constraint are typed as
L<Mu|/type/Mu> but default to the L<Any|/type/Any> type object.

Variables with the C<@> sigil are initialized with an empty
L<Array|/type/Array>; variables with the C<%> sigil are initialized with an
empty L<Hash|/type/Hash>.

The default value of a variable can be set with the C<is default> trait, and
re-applied by assigning C<Nil> to it:

    my Real $product is default(1);
    say $product;                       # OUTPUT: «1␤»
    $product *= 5;
    say $product;                       # OUTPUT: «5␤»
    $product = Nil;
    say $product;                       # OUTPUT: «1␤»

=head2 Default defined variables pragma

To force all variables to have a
L<definiteness|/language/mop#index-entry-syntax_DEFINITE-DEFINITE> constraint,
use the pragma C<use variables :D>. The pragma is lexically scoped and can be
switched off with C<use variables :_>.

=begin code :skip-test<compile-time error>
use variables :D;
my Int $i;
# OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Variable definition of type Int:D (implicit :D by pragma) requires an initializer ...
my Int $i = 1; # that works
{ use variables :_; my Int $i; } # switch it off in this block
=end code

Note that assigning L<Nil|/type/Nil> will revert the variable to its
default value, which is often not a definite value and as such would
fail the constraint:

=begin code
use variables :D;
my Int $x = 42;
$x = Nil;
# OUTPUT: «Type check failed in assignment to $x; expected type Int:D cannot be itself…»
=end code

As the name suggests, this pragma applies only to variables. To effect
the same behavior on parameters, use the C<use parameters :D> pragma
(currently NYI in Rakudo).

=head1 Special variables

Raku attempts to use long, descriptive names for special
variables. There are only three special variables that are extra
short.

=head2 Pre-defined lexical variables

There are three special variables that are always available:

=begin table

    Variable    Meaning            Scope

    $_          topic variable     every block
    $/          regex match        every sub / method
    $!          exceptions         every sub / method

=end table

X<|topic variable>
=head3 The C<$_> variable

C<$_> is the topic variable.  A fresh one is created in every B<block>.
It's also the default parameter for blocks that do not have an explicit
signature, so constructs like C<for @array { ... }> and C<given $var
{ ... }> bind the value or values of the variable to C<$_> by invoking
the block.

    for <a b c> { say $_ }  # binds $_ to 'a', 'b' and 'c' in turn
    say $_ for <a b c>;     # same, even though it's not a block
    given 'a'   { say $_ }  # binds $_ to 'a'
    say $_ given 'a';       # same, even though it's not a block

Because C<$_> is bound to the value of the iteration, you can also
assign to C<$_> if it is bound to something assignable.

    my @numbers = ^5;   # 0 through 4
    $_++ for @numbers;  # increment all elements of @numbers
    say @numbers;

    # OUTPUT: «1 2 3 4 5␤»

C<CATCH> blocks bind C<$_> to the exception that was caught. The C<~~>
smartmatch operator binds C<$_> on the right-hand side expression to the
value of the left-hand side.

Calling a method on C<$_> can be shortened by leaving off the variable name:

    .say;                   # same as $_.say

C<m/regex/> and C</regex/> regex matches and C<s/regex/subst/> substitutions
work on C<$_>:

    say "Looking for strings with non-alphabetic characters...";
    for <ab:c d$e fgh ij*> {
        .say if m/<-alpha>/;
    }

    # OUTPUT: «Looking for strings with non-alphabetic characters...
    #          ab:c
    #          d$e
    #          ij*␤»

X<|match variable>
=head3 The C<$/> variable

C<$/> is the match variable.  A fresh one is created in every B<routine>.
It is set to the result of the last L<Regex|/language/regexes>
match and so usually contains objects of type L<Match|/type/Match>.

    'abc 12' ~~ /\w+/;  # sets $/ to a Match object
    say $/.Str;         # OUTPUT: «abc␤»

The C<Grammar.parse> method also sets the caller's C<$/> to the resulting
L<Match|/type/Match> object.  For the following code:

=begin code :skip-test<needs ecosystem>
use XML::Grammar; # zef install XML
XML::Grammar.parse("<p>some text</p>");
say $/;

# OUTPUT: «｢<p>some text</p>｣
#           root => ｢<p>some text</p>｣
#            name => ｢p｣
#            child => ｢some text｣
#             text => ｢some text｣
#             textnode => ｢some text｣
#           element => ｢<p>some text</p>｣
#            name => ｢p｣
#            child => ｢some text｣
#             text => ｢some text｣
#             textnode => ｢some text｣␤»
=end code

Prior to the 6.d version, you could use C<$()> shortcut to get the
L<ast|/routine/ast> value from C<$/> L<Match|/type/Match> if that value is
truthy, or the stringification of the L<Match|/type/Match> object otherwise.

    'test' ~~ /.../;
    # 6.c language only:
    say $(); # OUTPUT: «tes␤»;
    $/.make: 'McTesty';
    say $(); # OUTPUT: «McTesty␤»;

This (non-)feature has been deprecated as of version 6.d.

=head4 X«Positional attributes|variable,$0;variable,$1»

C<$/> can have positional attributes if the L<Regex|/language/regexes> had
capture-groups in it, which are just formed with parentheses.

    'abbbbbcdddddeffg' ~~ / a (b+) c (d+ef+) g /;
    say $/[0]; # OUTPUT: «｢bbbbb｣␤»
    say $/[1]; # OUTPUT: «｢dddddeff｣␤»

These can also be accessed by the shortcuts C<$0>, C<$1>, C<$2>, etc.

    say $0; # OUTPUT: «｢bbbbb｣␤»
    say $1; # OUTPUT: «｢dddddeff｣␤»

To get all of the positional attributes, you can use C<$/.list> or C<@$/>.
Before 6.d, you can also use the C<@()> shortcut (no spaces inside the
parentheses).

    say @$/.join; # OUTPUT: «bbbbbdddddeff␤»

    # 6.c language only:
    say @().join; # OUTPUT: «bbbbbdddddeff␤»

This I<magic> behavior of C<@()> has been deprecated as of 6.d

=head4 X«Named attributes|variable,$<named>»

C<$/> can have named attributes if the L<Regex|/language/regexes> had named
capture-groups in it, or if the Regex called out to another Regex.

=for code
'I... see?' ~~ / \w+ $<punctuation>=[ <-[\w\s]>+ ] \s* $<final-word> = [ \w+ . ] /;
say $/<punctuation>; # OUTPUT: «｢....｣␤»
say $/<final-word>;  # OUTPUT: «｢see?｣␤»

These can also be accessed by the shortcut C«$<named>».

    say $<punctuation>; # OUTPUT: «｢....｣␤»
    say $<final-word>;  # OUTPUT: «｢see?｣␤»

To get all of the named attributes, you can use C<$/.hash> or C<%$/>.  Before
6.d language, you could also use the C<%()> shortcut (no spaces inside the
parentheses).

    say %$/.join;       # OUTPUT: «"punctuation     ....final-word  see?"␤»

    # 6.c language only
    say %().join;       # OUTPUT: «"punctuation     ....final-word  see?"␤»

This behavior has been deprecated as of the 6.d version.

=head4 Thread-safety issues

Because C<$/> is only defined per B<routine>, you are in fact
re-using the same C<$/> when you do matching in a loop.  In a single
threaded program, this is not an issue.  However, if you're going to
use C<hyper> or C<race> to have multiple threads do matching in
parallel, the sharing of the "outer" C<$/> becomes an issue, because
then it is being shared B<between> threads!  Fortunately, the solution
is very simple: define your own C<$/> inside the scope where you are
doing the matching.  For example, taking a source of text, running
a regex on it, and map that to a hash using parallel execution:

=begin code :preamble<my @source>
my %mapped = @source.race.map: {
    my $/;  # need one in this block to prevent racing issues
    m/foo (.*?) bar (.*)/;  # matches on $_, stores in $/
    $0 => $1   # short for $/[0] / $/[1]
}
=end code

X<|error variable>
=head3 The C<$!> variable

C<$!> is the error variable.  A fresh one is created in every B<routine>.
If a C<try> block or statement prefix catches an exception, that exception
is stored in C<$!>. If no exception was caught, C<$!> is set to C<Nil>.

Note that C<CATCH> blocks I<do not> set C<$!>. Rather, they set C<$_> inside
the block to the caught exception.

Also note that the same thread-safety issues apply to the use of C<$!> as
they do to C<$/>.

X<|$?FILE>X<|$?LINE>X<|::?CLASS>
=head2 Compile-time variables

All compile time variables have a question mark as part of the twigil. Being
I<compile time> they cannot be changed at runtime, however they are valuable in
order to introspect the program. The most common compile time variables are the
following:

=for table
    $?FILE         Which file am I in?
    $?LINE         Which line am I at? [indexed from 1]
    ::?CLASS       Which class am I in?
    %?RESOURCES    The files associated with the "Distribution" of the current compilation unit.

C<$?FILE> and C<$?LINE> are also available from L<CallFrame|/type/CallFrame> as
the L<C<file>|/type/CallFrame#method_file> and
L<C<line>|/type/CallFrame#method_line> methods, respectively.

=head3 C<%?RESOURCES>

C<%?RESOURCES> is a compile-time variable available to the code of a
X<Distribution>.

It contains a hash that provides compile and runtime access to files
associated with the Distribution of the current compilation unit. This hash
is used to access a special storage for C<Distribution>-wide static files
(such as examples of configuration files, templates or data files).

Files available via this variable need to be placed under C<resources>
directory:

=begin code :lang<text>
Module-Foo/
├── lib
│   └── Module
│       └── Foo.rakumod
├── META6.json
├── README.md
└── resources
    └── images
        └── foo.jpg
=end code

Additionally, a relative path (starting from the root resources directory of a
distribution) to a file is specified under C<"resources"> field in the
C<META6.json> file:

=begin code :lang<json>
"resources": [
    "images/foo.jpg"
]
=end code

X<|%?RESOURCES>
Every resource file is added to an installed Distribution and is
accessible using a C<Hash>-like access to C<%?RESOURCES>, returning a
C<Distribution::Resources> object:

=begin code :skip-test<resources-example>
my $foo-IO = %?RESOURCES<images/foo.jpg>;          # gets an object you can slurp
my $foo-IO = %?RESOURCES<images/foo.jpg>.absolute; # gets an absolute path to a file
my $foo-IO = %?RESOURCES<images/foo.jpg>.open;     # gets an opened IO::Handle to work with
=end code

Note that paths and names of resource files can be mangled in an
installed distribution, so do not rely on their values in any other
case besides using them as keys for the C<%?RESOURCES> variable.

The C<%?RESOURCES> variable is not implemented as a plain C<Hash>, but as an
instance of the C<Distribution::Resources> type, so do not expect to see
all available resource files in a distribution by printing or by using other
ways to inspect its value. Instead, use the API described above to
access particular files.

=head3 Introspection compile-time variables

X<|$?PACKAGE>X<|$?MODULE>X<|$?CLASS>X<|$?ROLE>
X<|$?TABSTOP>X<|$?NL>X<|$?DISTRIBUTION>

The following compile time variables allow for a deeper introspection:

=for table
    $?PACKAGE            Which package am I in?
    $?MODULE, ::?MODULE  Which module am I in? It contains the type of the module.
    $?CLASS              Which class am I in? (as variable)
    $?ROLE               Which role am I in? (as variable)
    $?TABSTOP            How many spaces is a tab in a heredoc or virtual margin?
    $?NL                 What a vertical newline "\n" means: LF, CR or CRLF
    $?DISTRIBUTION       The Distribution of the current compilation unit.

With particular regard to the C<$?NL>, see the L<newline
pragma|/language/pragmas>.

=head3 Rakudo-specific compile-time variables

These variables are Rakudo specific, with all the corresponding caveats:
=for table
$?BITS           Number of data-path bits of the platform the program is being compiled upon.

=head3 X<&?ROUTINE>

The compile time variable C<&?ROUTINE> provides introspection about which
routine the program is actually within. It returns an instance of
L<Sub|/type/Sub> attached to the current routine. It does support the method
C<.name> to obtain the name of the called routine, as well as C<.signature> and
others method related to C<Sub>:

    sub awesome-sub { say &?ROUTINE.name }
    awesome-sub; # OUTPUT: «awesome-sub␤»

It also allows also for recursion:

=begin code
my $counter = 10;
sub do-work {
    say 'Calling myself other ' ~ $counter-- ~ ' times';
    &?ROUTINE() if ( $counter > 0 );
}
do-work;
=end code

Note that, in a L<C«multi»|/language/functions#index-entry-declarator_multi-Multi-dispatch>,
C<&?ROUTINE> refers to the current candidate, I<not> the C<multi>
as a whole.

Thus, the following recursive definition does B<not> work:

=begin code
multi broken-fibonacci($n where * ≤ 1) { $n }
multi broken-fibonacci($n where * > 0) {
    &?ROUTINE($n - 1) + &?ROUTINE($n - 2)
}
=end code

If called, C<&?ROUTINE> would always refer to the second
multi candidate and would never dispatch to the first.  If
you want to use self-recursion for the whole C<proto>, either
use the function name or L<C«samewith»|language/functions#sub_samewith>.

=head3 X<&?BLOCK>

The special compile variable C<&?BLOCK> behaves similarly to
C<&?ROUTINE> but it allows to introspect a single block of code.
It holds a L<Sub|/type/Sub> and allows for recursion within the
same block:

=begin code
for '.' {
    .Str.say when !.IO.d;
    .IO.dir()».&?BLOCK when .IO.d # lets recurse a little!
}
=end code

=head3 X<$?DISTRIBUTION>

C<$?DISTRIBUTION> provides access to the L<Distribution|/type/Distribution> of
the current compilation unit. This gives module authors a way to reference other
files in the distribution by their original relative path names, or to view the
metadata (via the C<.meta> method), without needing to know the underlying file
structure (such as how C<CompUnit::Repository::Installation> changes the file
layout on installation).

=begin code :solo
unit module MyFoo;

sub module-version {
    say "MyFoo is version:";
    say $?DISTRIBUTION.meta<ver>;
}

sub module-source {
    say "MyFoo source code:";
    say $?DISTRIBUTION.content('lib/MyFoo.rakumod');
}
=end code

=head2 Dynamic variables

All dynamically scoped variables have the C<*> twigil, and their name is
(conventionally) written in uppercase.

X<|$*ARGFILES>X<|@*ARGS>
=head3 Argument related variables

These variables are related to the arguments passed to a script.

=head4 C<$*ARGFILES>

An L<IO::ArgFiles|/type/IO::ArgFiles> (an empty subclass of L<IO::CatHandle|/type/IO::CatHandle>) that uses C<@*ARGS>
as source files, if it contains any files, or C<$*IN> otherwise. When C<$*IN> is
used, its C<:nl-in>, C<:chomp>, C<:encoding>, and C<:bin> will be set on the
L<IO::ArgFiles|/type/IO::ArgFiles> object.

As of the 6.d version, C<$*ARGFILES> I<inside>
L<C«sub MAIN»|/language/functions#sub_MAIN> is always set to C<$*IN>, even when
C<@*ARGS> is not empty. See
L<the class documentation|/type/IO::ArgFiles#$*ARGFILES>
for examples and more context.

=head4 C<@*ARGS>

C<@*ARGS> is an array of C<Str> containing the arguments from the command line.

X<|&*ARGS-TO-CAPTURE>
=head4 C<&*ARGS-TO-CAPTURE>

A dynamic variable available inside any custom
L<C<ARGS-TO-CAPTURE>|/language/create-cli#sub_ARGS-TO-CAPTURE> subroutine
that can be used to perform the default argument parsing. Takes the same
parameters as are expected of the custom C<ARGS-TO-CAPTURE> subroutine.

X<|&*GENERATE-USAGE>
=head4 C<&*GENERATE-USAGE>

A dynamic variable available inside any custom
L<C<GENERATE-USAGE>|/language/create-cli#sub_GENERATE-USAGE> subroutine
that can be used to perform the default usage message creation. Takes the
same parameters as are expected of the custom C<GENERATE-USAGE> subroutine.

X<|$*IN>X<|$*OUT>X<|$*ERR>
=head3 Special filehandles: C<STDIN>, C<STDOUT> and C<STDERR>

For more information about special filehandles please see also the L<Input and
Output|/language/io> page and the L<IO::Special|/type/IO::Special> class. L<IO::Handle|/type/IO::Handle> contains
several examples of using C<$*IN> for reading standard input.

=item C<$*IN>
Standard input filehandle, AKA I<STDIN>.

=item C<$*OUT>
Standard output filehandle, AKA I<STDOUT>.

=item C<$*ERR>
Standard error filehandle, AKA I<STDERR>.

=head3 Runtime environment

These dynamic variables contain information related to the environment the
script or program is running in.

X<|%*ENV>
=head4  C<%*ENV>

Operating system environment variables. Numeric values are provided
as L<allomorphs|/language/glossary#index-entry-Allomorph>.

X<|$*REPO>
=head4 C<$*REPO>

This variable holds information about modules installed/loaded.

X<|$*INIT-INSTANT>
=head4 C<$*INIT-INSTANT>

C<$*INIT-INSTANT> is an L<Instant|/type/Instant> object representing program
startup time. In particular, this is when the core code starts up, so the value
of C<$*INIT-INSTANT> may be a few milliseconds earlier than C<INIT now> or even
C<BEGIN now> executed in your program.

X<|$*TZ>
=head4 C<$*TZ>

C<$*TZ> is a dynamic variable intended to contain an object with information
about the system's local timezone.  It should numify to the number of
B<seconds> from GMT.

If not set explicitly, it contains just an integer value without any
further information, set the first time C<$*TZ> is accessed.  Any
daylight saving time changes occurring during the duration of the
process will B<not> be seen in that case.

X<|$*CWD>
=head4 C<$*CWD>

It contains the C<C>urrent C<W>orking C<D>irectory.

X<|$*KERNEL>
=head4 C<$*KERNEL>

C<$*KERNEL> contains a L<C<Kernel> instance|/type/Kernel>, the C<.gist> of it
being the current running kernel.

    say $*KERNEL; # OUTPUT: «linux (4.4.92.31.default)␤»

X<|$*DISTRO>
=head4 C<$*DISTRO>

This object (of type C<Distro>) contains information about the current operating
system distribution. For instance:

    say "Some sort of Windows" if $*DISTRO.is-win;

C<$*DISTRO.name> takes a set of values that depend on the operating system.
These names will vary with version and implementation, so you should
double-check and test before using them in your programs; since these names are
implementation defined and not in the specification, they could vary and change
at any moment.

The C<$*DISTRO> gist is displayed by using C<say>:

    say $*DISTRO; # OUTPUT: «debian (9.stretch)␤»

This shows additional information on the operating system and version it's
using, but as a matter of fact, this variable contains information which is
useful to create portable programs, such as the path separator:

    say $*DISTRO.raku;
    # OUTPUT: «Distro.new(release => "42.3", is-win => Bool::False,
    #          path-sep => ":", name => "opensuse",
    #          auth => "https://www.opensuse.org/", version => v42.3,
    #          signature => Blob, desc => "2018-12-13T08:50:59.213619+01:00")␤»


X<|$*VM>
=head4 C<$*VM>

This variable contains the current virtual machine running the code, as well as
additional information on the inner workings of aforementioned VM.

    say $*VM.precomp-ext, " ", $*VM.precomp-target; # OUTPUT: «moarvm mbc␤»

These two methods, for instance, will show the extension used in the precompiled
bytecode scripts and the target used. This is what is found in the Moar Virtual
Machine, but it could also vary with version and implementation. Other VM, such
as Java, will show different values for them. C<$*VM.config> includes all
configuration values used to create the virtual machine, e.g.

    say $*VM.config<versionmajor>, ".", $*VM.config<versionminor>;
    # OUTPUT: «2018.11␤»

which are the version of the virtual machine, generally the same one as the one
used in the interpreter and the overall Raku environment.

X<|$*RAKU>
=head4 C<$*RAKU>

This object of the L<C<Raku>|/type/Raku> class contains information on the
current implementation of the Raku language:

    say $*RAKU.compiler.version; # OUTPUT: «v2020.01␤»

but its gist includes the name of the language, followed by the major
version of the compiler:

    say $*RAKU; # OUTPUT: «Raku (6.d)␤»

It stringifies to C<Raku>:

    $*RAKU.put; # OUTPUT: «Raku␤»

B<Note:> Before Rakudo version 2020.1, this information was only
available through the C<$*PERL> variable. Since Rakudo version 2020.1,
it is available through both the C<$*RAKU> and the C<$*PERL> variables.

X<|$*PERL>
=head4 C<$*PERL>

For the foreseeable future, the same as C<$*RAKU>.  Will be deprecated at
some point.

X<|$*PID>
=head4 C<$*PID>

Object containing an integer describing the current Process IDentifier
(operating system dependent).

X<|$*PROGRAM-NAME>
=head4 C<$*PROGRAM-NAME>

This contains the path to the current executable as it was entered on the
command line, or C<-e> if raku was invoked with the -e flag.

X<|$*PROGRAM>
=head4 C<$*PROGRAM>

Contains the location (in the form of an C<IO::Path> object) of the Raku
program being executed.

X<|&*EXIT>
=head4 C<&*EXIT>

This is a L<Callable|/type/Callable> that contains the code that will be
executed when doing an C<exit()> call.  Intended to be used in situations where
Raku is embedded in another language runtime (such as Inline::Perl6 in Perl).

X<|$*EXECUTABLE>
=head4 C<$*EXECUTABLE>

Contains an C<IO::Path> absolute path of the raku executable that is currently
running.

X<|$*EXECUTABLE-NAME>
=head4 C<$*EXECUTABLE-NAME>

Contains the name of the Raku executable that is currently running. (e.g.
raku-p, raku-m). Favor C<$*EXECUTABLE> over this one, since it's not
guaranteed that the raku executable is in C<PATH>.

X<|$*USAGE>
=head4 C<$*USAGE>

This is the default usage message generated from the
signatures of C<MAIN> subs available from inside
C<sub MAIN> and C<sub USAGE>. The variable is I<read-only>.

X<|$*USER>
=head4 C<$*USER>

An C<Allomorph> with information about the user that is running the program. It
will evaluate to the username if treated as a string and the numeric user id if
treated as a number.

X<|$*GROUP>
=head4 C<$*GROUP>

An C<Allomorph> with the primary group of the user who is running the program.
It will evaluate to the groupname only if treated as a string and the numeric
group id if treated as a number.

X<|$*HOMEDRIVE>
=head4 C<$*HOMEDRIVE>

Contains information about the "home drive" of the user that is running the
program on Windows. It's not defined in other operating systems.

X<|$*HOMEPATH>
=head4 C<$*HOMEPATH>

Contains information about the path to the user directory that is running the
program on Windows. It's not defined in other operating systems.

X<|$*HOME>
=head4 C<$*HOME>

Contains an L<IO::Path|/type/IO::Path> object representing the "home directory" of the user
that is running the program. Uses C«%*ENV<HOME>» if set.

On Windows, uses C«%*ENV<HOMEDRIVE> ~ %*ENV<HOMEPATH>». If the home directory
cannot be determined, it will be L<Any|/type/Any>.

X<|$*SPEC>
=head4 C<$*SPEC>

Contains the appropriate L<IO::Spec|/type/IO::Spec> sub-class for the platform that the program
is running on. This is a higher-level class for the operating system; it will
return C<Unix>, for instance, in the case of Linux (in the form of the
C<IO::Spec> class used for the current implementation).

X<|$*TMPDIR>
=head4 C<$*TMPDIR>

This is an L<IO::Path|/type/IO::Path> object representing the "system temporary directory" as
determined by L«C<.tmpdir IO::Spec::* method>|/routine/tmpdir».

X<|$*THREAD>
=head4 C<$*THREAD>

Contains a L<Thread|/type/Thread> object representing the currently executing
thread.

X<|$*SCHEDULER>
=head4 C<$*SCHEDULER>

This is a L<ThreadPoolScheduler|/type/ThreadPoolScheduler> object representing
the current default scheduler.

By default this imposes a maximum of 64 threads on the methods C<.hyper>,
C<.race> and other thread-pool classes that use that scheduler such as
C<Promise>s or C<Supply>s. This is, however, implementation, dependent and might
be subject to change. To change the maximum number of threads, you can either
set the environment variable C<RAKUDO_MAX_THREADS> before running raku or
create a scoped copy with the default changed before using them:

    my $*SCHEDULER = ThreadPoolScheduler.new( max_threads => 128 );

This behavior is not tested in the spec tests and is subject to change.

X<|$*SAMPLER>
=head4 C<$*SAMPLER>

The current L<Telemetry::Sampler|/type/Telemetry::Sampler> used for making snapshots of system state.
Only available if L<Telemetry|/type/Telemetry> has been loaded.

X<|$*USAGE>
=head4 C<$*USAGE>

This is a L<Str|/type/Str> object that holds value of the auto-generated USAGE
message.

=for code
sub MAIN($a, :$b, UInt :$ehehe) {
    say $*USAGE; # OUTPUT: «Usage:␤  my-script.raku [-a=<Int>] [-b=<Str>] [--<opts>=...]»
}

It is accessible only inside of MAIN sub.

=head3 Runtime variables

These variables affect the behavior of certain functions, and in some cases its
value can be changed during runtime.

X<|$*COLLATION>
=head4 C<$*COLLATION>

This is a L<Collation|/type/Collation> object that can be used to
configure Unicode collation levels.

X<|$*TOLERANCE>
=head4 C<$*TOLERANCE>

Variable used by the L<C<=~=>|/routine/=~=> operator, and any operations that
depend on it, to decide if two values are approximately equal. Defaults to
C<1e-15>.

X<|$*DEFAULT-READ-ELEMS>
=head4 C<$*DEFAULT-READ-ELEMS>

Affects the number of bytes read by default by
L<C<IO::Handle.read>|/type/IO::Handle#method_read>. Its default value is 65536.

=head1 Naming conventions

It is helpful to know our naming conventions in order to understand what codes
do directly. However, there is not yet (and might never be) an official list of;
still, we list several conventions that are widely held.

=item1 Subs and methods from the built-ins library try to have single-word names
when a good one could be found. In cases where there are two or more words
making up a name, they are separated by a "-".

=item1 Compounds are treated as a single word, thus C<substr>, C<subbuf>, and
C<deepmap> (just like we write "starfish", not "star fish" in English).

=item1 Subs and methods that are automatically called for you at special times
are written in uppercase. This includes the C<MAIN> sub, the C<AT-POS> and
related methods for implementing container types, along with C<BUILD> and
C<DESTROY>.

=item1 Type names are camel case, except for native types, which are lowercase.
For the exception, you can remember it by: they are stored in a more compact
way, so they names look smaller too.

=item1 Built-in dynamic variables and compile-time variables are always
uppercase, such like C<$*OUT>, C<$?FILE>.

=item1 Methods from the MOP and other internals use "_" to separate multiple
words, such like C<add_method>.

=end pod

# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6
